package com.lw.leetcode.stack.b;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * 1976. 到达目的地的方案数
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/17 21:28
 */
public class CountPaths {

    public static void main(String[] args) {
        CountPaths test = new CountPaths();

        // 4
        int n = 7;
        int[][] roads = {{0, 6, 7}, {0, 1, 2}, {1, 2, 3}, {1, 3, 3}, {6, 3, 3}, {3, 5, 1}, {6, 5, 1}, {2, 5, 1}, {0, 4, 5}, {4, 6, 2}};

        // 1
//        int n = 2;
//        int[][] roads = {{1, 0, 10}};

        System.out.println(Integer.MAX_VALUE);

        int i = test.countPaths(n, roads);
        System.out.println(i);
    }


    public int countPaths(int n, int[][] roads) {
        List<Long>[] arr = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            arr[i] = new ArrayList<>();
        }
        for (int[] road : roads) {
            int a = road[0];
            int b = road[1];
            long c = road[2];
            arr[a].add((c << 32) + b);
            arr[b].add((c << 32) + a);
        }

        long[] flags = new long[n];
        long[] flags2 = new long[n];

        int[] ts = new int[n];
        flags[0] = 1;
        flags2[0] = 1;

        PriorityQueue<Long> queue = new PriorityQueue<>();
        queue.add((1L) << 12);
        long v = Long.MAX_VALUE;
        while (!queue.isEmpty()) {
            Long poll = queue.poll();
            long sum = poll >> 12;
            if (sum >= v) {
                return (int) flags2[n - 1];
            }
            int item = (int) (poll & 0XFFF);
            if (flags[item] < sum || ts[item] == 1) {
                continue;
            }
            ts[item] = 1;
            List<Long> values = arr[item];
            long l = flags2[item];
            for (Long value : values) {
                int to = value.intValue();
                long c = (value >> 32) + sum;
                if (flags[to] == 0 || flags[to] > c) {
                    flags[to] = c;
                    flags2[to] = l;
                    queue.add((c << 12) + to);
                } else if (flags[to] == c) {
                    flags2[to] = (flags2[to] + l) % 1000000007;
                }
                if (to == n - 1) {
                    v = Math.min(v, c);
                }
            }
        }
        return (int) flags2[n - 1];
    }

}
